package com.mlink.plugin.file;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;


import com.siicfm.oa.MainActivity;

import org.apache.cordova.CordovaActivity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

public class UpLoadFileActviity extends CordovaActivity implements CallBack {
    private static final String TAG = "MainActivity";
    private SharedPreferences.Editor ed;
    private SharedPreferences sp;
    private EditText edName, edpassWord;
    private LinearLayout loginLayout;
    private RelativeLayout progress;

    private String path = "", fileName = "", userId = "";
    private boolean isUpLoad = false;
    Intent intetn = null;
    private static final int LOGINYES = 1, LOGINNO = 2, UPLOADYES = 3, UPLOADNO = 4;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int stats = msg.what;
            String message = (String) msg.obj;
            switch (stats) {
                case LOGINYES:
                    try {
                        String json = message;
                        JSONObject data = new JSONObject(json);
                        JSONObject body = data.getJSONObject("BODY");
                        String minUserId = body.getString("userId");
                        userId = minUserId;
                        ed.putString("userMessage", message);
                        ed.putString("userId", userId);
                        ed.commit();
                        loginLayout.setVisibility(View.GONE);
                        Toast.makeText(UpLoadFileActviity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        getData(intetn);
                    } catch (JSONException e) {
                        Log.d(TAG, "onResponse: " + e.getMessage());
                        e.printStackTrace();
                    }
                    break;
                case LOGINNO:
                    Toast.makeText(UpLoadFileActviity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    break;
                case UPLOADYES:
                    progress.setVisibility(View.GONE);
                    Toast.makeText(UpLoadFileActviity.this, "上传成功", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(UpLoadFileActviity.this, MainActivity.class));
                    finish();
                    break;
                case UPLOADNO:
                    progress.setVisibility(View.GONE);
                    Toast.makeText(UpLoadFileActviity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getResources().getIdentifier("activity_cordova_upload", "layout", getPackageName()));
        //获取权限
        getPermission();
        init();
    }

    public void init() {
        sp = this.getSharedPreferences("UserInfo", 1);
        ed = sp.edit();
        //初始化代码
        edName = (EditText) findViewById(getResources().getIdentifier("userName_ed", "id", getPackageName()));
        edpassWord = (EditText) findViewById(getResources().getIdentifier("passWord_ed", "id", getPackageName()));
        loginLayout = (LinearLayout) findViewById(getResources().getIdentifier("login_ly", "id", getPackageName()));
        progress = (RelativeLayout) findViewById(getResources().getIdentifier("progress", "id", getPackageName()));
        findViewById(getResources().getIdentifier("login_btn", "id", getPackageName())).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //登录按钮
                String userName = edName.getText().toString();
                String password = edpassWord.getText().toString();
                utils.Login(UpLoadFileActviity.this, userName, password);
            }
        });
    }

    //系统自带的更新Intent的方法
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        userId = sp.getString("userId", "");
        intetn = getIntent();
        Log.d("aaa", "onResume: ");
        if (userId.equals("")) {
            Log.d(TAG, "onResume: 没有userId");
            loginLayout.setVisibility(View.VISIBLE);
            Toast.makeText(this, "没有登陆", Toast.LENGTH_SHORT).show();
        } else {
            loginLayout.setVisibility(View.GONE);
            Log.d(TAG, "onResume: getData");
            getData(intetn);
        }
    }

    private void getData(Intent intent) {
        Uri uri = intent.getData();
        if (uri != null) {
            try {
                File file = new File(new URI(uri.toString()));
                path = file.getAbsolutePath();
                Log.d(TAG, "onResume: " + file.getAbsolutePath());
                if (path != null && !path.equals("")) {
                    int startIndex = path.lastIndexOf("/");
                    if (startIndex > 0) {
                        fileName = path.substring(startIndex, path.length()).replace("/", "");
                        progress.setVisibility(View.VISIBLE);
                        UpLoad();
                    }
                }
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "文件获取错误", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "getData: 没有文件");
        }
    }

    private void UpLoad() {
        if (!fileName.equals("") && !path.equals("")) {
            Log.d(TAG, "fileName: " + fileName + "....path" + path);
            File file = new File(path);
            if (file.exists()) {
                isUpLoad = true;
                Log.d("UpLoadUtil", "userId:" + userId);
                if (getPermission()) {
                    if (!userId.equals("")) {
                        utils.testUploadFile(utils.url, userId, fileName, path, this);
                    } else {
                        Toast.makeText(this, "userId不能为空", Toast.LENGTH_LONG).show();
                    }

                }
            } else {
                Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(UpLoadFileActviity.this, "没有选择文件", Toast.LENGTH_SHORT).show();
        }
    }

    //登录和上传成功和失败的回掉
    @Override
    public void setResponse(final String response, String type) {
        Message msg = handler.obtainMessage();
        if (type.equals("login")) {
            if (response.equals("error")) {
                msg.what = LOGINNO;
            } else {
                msg.what = LOGINYES;
            }
        } else if (type.equals("upload")) {
            if (response.equals("error")) {
                msg.what = UPLOADNO;
            } else {
                msg.what = UPLOADYES;
            }
        }
        msg.obj = response;
        handler.sendMessage(msg);
    }

    //权限申请
    @SuppressLint("NewApi") private boolean getPermission() {
        boolean isPermission = false;
        //申请权限
        if (ContextCompat.checkSelfPermission(UpLoadFileActviity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1001);
        } else {
            isPermission = true;
        }
        return isPermission;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1001: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //授权成功
                    Log.d(TAG, "onRequestPermissionsResult: 111");
                } else {
                    //不授权
                    Log.d(TAG, "onRequestPermissionsResult: 222");
                }
                return;
            }
        }
    }
}
